//
//  SEInspTableView.swift
//  SBSafetyApp
//
//  Created by Lina on 2022/12/20.
//

import Foundation
import UIKit

class SEInspTableView: UIView {
    let tableView = UITableView(frame: .zero, style: .plain)

    var emptyType: EmptyViewEnum = .normal
    
    var datas : [ParListModal?] = [] {
        didSet {
            tableView.tableShowEmpty(withDataCount: datas.count, enumS: emptyType)
            tableView.reloadData()
        }
    }
    
    var needReload:(() -> ())?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    // MARK: - Setup
    
    func setupUI() {
        tableView.separatorStyle = .none
        tableView.showsVerticalScrollIndicator = false
        tableView.backgroundColor = .bg
        tableView.dataSource = self
        tableView.delegate = self
        addSubview(tableView)
        tableView.snp.makeConstraints { (make) in
            make.top.bottom.left.right.equalToSuperview()
        }
    }
}

extension SEInspTableView: UITableViewDataSource, UITableViewDelegate {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return datas.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let data = datas[indexPath.row]
        let ID : String = "InspListCell"
            
        var cell = tableView.dequeueReusableCell(withIdentifier: ID)
        if cell == nil {
            cell = InspListCell(style: .subtitle, reuseIdentifier: ID)
        }
        
        (cell as? InspListCell)?.reload(withModal: data)
        (cell as? InspListCell)?.startBtn.addTarget(self, action: #selector(startTapped), for: .touchUpInside)
        (cell as? InspListCell)?.closeBtn.addTarget(self, action: #selector(closeTapped), for: .touchUpInside)
        (cell as? InspListCell)?.confirmedBtn.addTarget(self, action: #selector(toBeConfirmedTapped), for: .touchUpInside)
        return cell!
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 186
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let data = datas[indexPath.row]
        let vc = InspListDetailVC(withModal: data!)
        getFirstViewController()?.navigationController?.pushViewController(vc, animated: true)
    }
    
    // 巡检确认
    @objc func toBeConfirmedTapped(_ sender: BSModalButton) {
        if sender.parItem == nil { return }
        getFirstViewController()?.navigationController?.pushViewController(InspListDetailConfirmVC(withModal: sender.parItem!), animated: true)
    }
    
    // 开始巡检
    @objc func startTapped(_ sender: BSModalButton) {
        if sender.parItem == nil { return }
        
        let e_param = EngineerParam(formId: sender.parItem?.formId, local: sender.parItem?.local)
        let fdvc = FaceDetectVC()
        fdvc.didSelectImageWith = { (img) -> () in
            fdvc.navigationController?.popViewController(animated: true)
//            e_param.sign = img.imgToBase64()
            self.didStarted(withParam: e_param, parItem: sender.parItem, img: img)
        }
        
        getFirstViewController()?.navigationController?.pushViewController(fdvc, animated: true)
    }
    
    func didStarted(withParam e_param: EngineerParam, parItem: ParListModal?, img: UIImage) {
        showToastActivity()
        let path = FilesManager.shared.saveImage(img: img.resizedTo1MB() ?? img)!
        API.postEngineerArrive(withParam: e_param, imagePath: path) { responseModel in
            DispatchQueue.main.async {
                self.hideToastActivity()
                if responseModel.errorCode == .Success {
                    self.showToast(witMsg: responseModel.errorMessage)
                    Utils.delay(second: 1) {
                        self.needReload?()
                        let vc = SEInspListDetailVC(withModal: parItem!)
                        self.getFirstViewController()?.navigationController?.pushViewController(vc, animated: true)
                    }
                }
            }
        }
    }
    
    // 结束巡检
    @objc func closeTapped(_ sender: BSModalButton) {
        if sender.parItem == nil { return }
        let vc = SEInspListDetailVC(withModal: sender.parItem!)
        getFirstViewController()?.navigationController?.pushViewController(vc, animated: true)
    }
}
